<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.keyword" class="filter-item search" style="width: 150px;" placeholder="请输入要搜索的内容" />
      <el-button class="filter-item" type="primary" plain icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">新增</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="menuList"
      style="width: 100%;margin-bottom: 20px;"
      row-key="id"
      border
      stripe
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="id" label="ID" sortable type="" />
      <el-table-column prop="meta.title" label="标题" />
      <el-table-column label="图标">
        <template slot-scope="scope">
          <i :class="scope.row.meta.icon" />
        </template>
      </el-table-column>
      <el-table-column prop="component" label="组件路径" />
      <el-table-column prop="status" label="是否可见">
        <template slot-scope="scope">
          {{ scope.row.status === 1 ? '显示' : '隐藏' }}
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" />
      <el-table-column prop="date" label="创建时间" />
      <el-table-column fixed="right" label="操作" width="100">
        <template slot-scope="{row, $index}">
          <el-button type="text" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="text" size="small" @click="handleDelete(row, $index)">移除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">

      <el-form ref="dataForm" :rules="rules" :model="menuForm">
        <el-form-item label="菜单类型" :label-width="formLabelWidth">
          <el-radio-group v-model="menuForm.type">
            <el-radio-button label="1">目录</el-radio-button>
            <el-radio-button label="2">菜单</el-radio-button>
            <el-radio-button label="3">按钮</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-col :md="8">
            <el-form-item v-if="menuForm.type == 3" label="权限标识" prop="permission" :label-width="formLabelWidth">
              <el-input v-model="menuForm.permission" placeholder="填写权限标识" autocomplete="off" />
            </el-form-item>
            <el-form-item v-else label="路由地址" prop="path" :label-width="formLabelWidth">
              <el-input v-model="menuForm.path" placeholder="路由地址(/:path)" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :md="8">
            <el-form-item label="标题" :label-width="formLabelWidth">
              <el-input v-model="menuForm.meta.title" placeholder="填写标题" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-form-item>

        <el-form-item v-if="menuForm.type != 3">
          <el-col :md="8">
            <el-form-item label="路由名称" prop="name" :label-width="formLabelWidth">
              <el-input v-model="menuForm.name" placeholder="路由的名字" autocomplete="off" />
            </el-form-item>
          </el-col>
          <el-col :md="8">
            <el-form-item label="组件路径" prop="component" :label-width="formLabelWidth">
              <el-input v-model="menuForm.component" placeholder="组件路径(path/path)" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-form-item>

        <el-form-item v-if="menuForm.type != 3">
          <el-col :md="8">
            <el-form-item label="菜单排序" :label-width="formLabelWidth">
              <el-input-number v-model="menuForm.sort" controls-position="right" :min="1" :max="20" @change="handleOrderChange" />
            </el-form-item>
          </el-col>
          <el-col :md="8">
            <el-form-item label="图标" :label-width="formLabelWidth">
              <el-input v-model="menuForm.meta.icon" prefix-icon="el-icon-search" placeholder="点击选择图标" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-form-item>

        <el-form-item v-if="menuForm.type != 3">
          <el-col :md="8">
            <el-form-item label="可见性" :label-width="formLabelWidth">
              <el-radio-group v-model="menuForm.hidden">
                <el-radio-button label="0">显示</el-radio-button>
                <el-radio-button label="1">隐藏</el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="高亮菜单" :label-width="formLabelWidth">
              <el-input v-model="menuForm.meta.activeMenu" placeholder="指定高亮侧边栏菜单" autocomplete="off" />
            </el-form-item>
          </el-col>
        </el-form-item>

        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-radio-group v-model="menuForm.status">
            <el-radio-button label="1">正常</el-radio-button>
            <el-radio-button label="0">禁用</el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="menuForm.type">
          <el-col :md="16">
            <el-form-item label="上级目录" :label-width="formLabelWidth">
              <span v-if="treeLoading">加载中...</span>
              <treeselect v-else v-model="menuForm.parent_id" :options="treeList" />
            </el-form-item>
          </el-col>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleData()">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import checkPermission from '@/utils/permission' // 权限判断函数
import { getMenuList, handleMenu, deleteMenu, getTreeList } from '@/api/menu'
import permission from '@/directive/permission/index.js' // 权限判断指令
import Treeselect from '@riophae/vue-treeselect' // 树形下拉选择组件
import '@riophae/vue-treeselect/dist/vue-treeselect.css' // 树形下拉选择组件样式

export default {
  name: 'Menu',
  directives: { permission },
  components: { Treeselect },
  data() {
    return {
      permissionRoles: this.$store.state.user.permissionRoles,
      menuList: [],
      treeList: [],
      listLoading: false,
      treeLoading: true,
      dialogFormVisible: false,
      dialogStatus: '',
      listQuery: {
        keyword: ''
      },
      textMap: {
        update: '编辑菜单',
        create: '新增菜单'
      },
      menuForm: {
        type: 1, // 类型
        status: 1, // 状态
        hidden: 0, // 菜单隐藏
        sort: 0, // 排序码
        path: '', // 路由地址
        name: '', // 路由名称
        component: '', // 组件路径
        parent_id: 0, // 上级目录
        permission: '', // 权限标识
        meta: {
          title: '', // 标题
          icon: '', // 图标
          activeMenu: '' // 菜单高亮
        }
      },
      formLabelWidth: '90px', // 表单label宽度
      rules: {
        permission: [{ required: true, message: '权限标识不能为空！', trigger: 'blur' }],
        path: [{ required: true, message: '路由地址不能为空！', trigger: 'blur' }],
        name: [{ required: true, message: '路由名称不能为空！', trigger: 'blur' }],
        component: [{ required: true, message: '组件路径不能为空！', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getMenuList() // 获取菜单列表
  },
  methods: {
    checkPermission,
    async getMenuList() {
      this.listLoading = true
      const res = await getMenuList(this.listQuery)
      this.listLoading = false
      this.menuList = res.data
    },
    async getTreeList(obj) {
      const res = await getTreeList(obj)
      this.treeList = res.data
      this.treeLoading = false
    },
    // 重置数据
    resetMenuForm() {
      this.menuForm = {
        type: 1,
        status: 1,
        hidden: 0,
        sort: 0,
        path: '',
        name: '',
        component: '',
        parent_id: 0,
        meta: {
          title: '',
          icon: '',
          activeMenu: ''
        }
      }
    },
    // 创建菜单
    handleCreate() {
      this.resetMenuForm()
      this.getTreeList()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 点击编辑
    handleEdit(row) {
      this.getTreeList({ id: row.id })
      this.menuForm = Object.assign({}, row) // copy obj
      this.menuForm.hidden = this.menuForm.hidden ? 1 : 0
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.menuForm.meta.title === '') {
            this.$message.error('请填写标题')
            return
          }
          handleMenu(this.menuForm).then(response => {
            this.menuList = response.data
            this.dialogFormVisible = false
            this.$notify({
              title: '操作成功',
              message: '菜单已创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('你确定要删除此菜单吗?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const res = await deleteMenu(row.id)
          this.menuList = res.data
          this.$notify({
            title: '成功',
            message: '删除成功！',
            type: 'success',
            duration: 2000
          })
        })
        .catch(err => { console.error(err) })
    },
    // 点击排序按钮处理
    handleOrderChange(value) {
      console.log(value)
    },
    handleFilter(query) {
      this.getMenuList()
    }
  }
}
</script>
